package com.gears_software.sxdc.dccx.ui.activity;

import android.app.Activity;
import android.os.CountDownTimer;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.gears_software.sxdc.dccx.R;
import com.gears_software.sxdc.dccx.application.DCCXApplication;
import com.gears_software.sxdc.dccx.data.finder.IMemberFinder;
import com.gears_software.sxdc.dccx.data.finder.util.GearsErrorHandler;
import com.gears_software.sxdc.dccx.data.model.ResultModel;
import com.gears_software.sxdc.dccx.data.model.TokenModel;
import com.gears_software.sxdc.dccx.data.model.request.RMemberLoginModel;
import com.gears_software.sxdc.dccx.data.sharedPreference.DCCXSp_;
import com.gears_software.sxdc.dccx.ui.event.UpdateDriverMemberAndOrderEvent;
import com.gears_software.sxdc.dccx.ui.event.UpdateDriverTripEvent;
import com.gears_software.sxdc.dccx.ui.util.MaterialDialogProgress;
import com.gears_software.sxdc.dccx.ui.util.OttoBus;
import com.j256.ormlite.stmt.query.In;
import com.sdsmdg.tastytoast.TastyToast;

import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.App;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.androidannotations.rest.spring.annotations.RestService;

import qiu.niorgai.StatusBarCompat;

/**
 * Created by SunMuran on 2017/7/25.
 */
@EActivity(R.layout.activity_login)
public class LoginActivity extends Activity {
    @App
    DCCXApplication app;
    @Pref
    DCCXSp_ sp;
    @ViewById
    TextView actionbar_title;
    @ViewById
    TextView back_icon;
    @ViewById
    TextView right_icon;
    @ViewById
    Button btn_getcode;
    @ViewById
    Button btn_login;
    @ViewById
    EditText et_phone_number;
    @ViewById
    EditText et_authentication_code;
    @RestService
    IMemberFinder memberFinder;
    @Bean
    GearsErrorHandler errorHandler;
    @Bean
    OttoBus bus;
    TimeCode timeCode;
    MaterialDialogProgress progress;

    @AfterViews
    void created() {
        actionbar_title.setText("快速登录");
        initIconfont();
        StatusBarCompat.setStatusBarColor(this, ContextCompat.getColor(this, R.color.colorActionbar));

        memberFinder.setRestErrorHandler(errorHandler);
        timeCode = new TimeCode(6000, 1000);
        progress = new MaterialDialogProgress(this);
    }

    void initIconfont() {
        back_icon.setTypeface(app.iconfont);
        back_icon.setText(R.string.back_icon);
        right_icon.setVisibility(View.GONE);
    }

    @Click
    void btn_getcode() {
        if (et_phone_number.getText().toString().equals("")) {
            TastyToast.makeText(this, "请输入手机号", app.SHORT, app.WARNING);
        } else if (et_phone_number.getText().toString().length() != 11) {
            TastyToast.makeText(this, "请输入正确的手机号", app.SHORT, app.WARNING);
        } else {
            progress.show("正在获取验证码，请等待...");
            timeCode.start();
            getCode();
        }

    }

    @Background
    void getCode() {
        String phone = et_phone_number.getText().toString();
        ResultModel<Object> res = memberFinder.getTelephoneCode(phone);
        showCodeResult(res);

    }

    @UiThread
    void showCodeResult(ResultModel<Object> res) {
        if (res != null) {
            if (!res.getErrno().equals("0")) {
                TastyToast.makeText(this, res.getErrmsg(), app.SHORT, app.ERROR);
            }
        }
        progress.dismiss();
    }

    @Click
    void btn_login() {
        if (et_phone_number.getText().toString().equals("")) {
            TastyToast.makeText(this, "请输入手机号", app.SHORT, app.WARNING);
        } else if (et_phone_number.getText().toString().length() != 11) {
            TastyToast.makeText(this, "请输入正确的手机号", app.SHORT, app.WARNING);
        } else if (et_authentication_code.getText().toString().equals("")) {
            TastyToast.makeText(this, "请输入验证码", app.SHORT, app.WARNING);
        } else {
            getLogin();
        }

    }

    @Background
    void getLogin() {
        RMemberLoginModel loginModel = new RMemberLoginModel();
        loginModel.setAddress("140100");
        loginModel.setUsertype("2");
        loginModel.setCode(et_authentication_code.getText().toString());
        loginModel.setTelephone(et_phone_number.getText().toString());
        loginModel.setDeviceId(sp.deviceId().get());
        ResultModel<TokenModel> res = memberFinder.loginAndRegister(loginModel);
        showLoginResult(res);
    }

    @UiThread
    void showLoginResult(ResultModel<TokenModel> res) {
        if (res != null) {
            if (res.getErrno().equals("0")) {
                if (res.getData() != null) {
                    TokenModel tokenModel = res.getData();
                    sp.token().put(tokenModel.getToken());
                    sp.refreshToken().put(tokenModel.getRefreshToken());
                    sp.userId().put(tokenModel.getId());
                    bus.post(new UpdateDriverMemberAndOrderEvent());
                }
                app.needLogin = true;
                setResult(1);
                this.finish();

            } else {
                TastyToast.makeText(this, res.getErrmsg(), app.SHORT, app.ERROR);
            }
        }
    }


    // 倒计时实现类


    class TimeCode extends CountDownTimer {

        public TimeCode(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            btn_getcode.setEnabled(true);
            btn_getcode.setBackgroundResource(R.drawable.button_red_bg);
            btn_getcode.setText("重获验证码");
            et_phone_number.setEnabled(true);
        }

        @Override
        public void onTick(long arg0) {
            btn_getcode.setBackgroundResource(R.drawable.button_bg_gray);
            btn_getcode.setEnabled(false);
            btn_getcode.setText(arg0 / 1000 + "秒");
            et_phone_number.setEnabled(false);
        }
    }

    @Click
    void back_icon() {
        finish();
    }
}
